<?php

namespace App\Http\Controllers\Mobile\Company\Auth;
use App\Jobs\CompanyRegisterEmail;
use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyUser;
use App\Models\Company\CompanyVisitRecord;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth,Validator,CustomPassword;


class AuthController extends Controller{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    //登录以后跳转到什么位置
    protected $redirectTo = 'mobile/company/welcome';
    //退出以后跳转到什么位置
    protected $redirectAfterLogout = '/mobile';
    protected $guard = 'company';
    protected $loginView = 'default.mobile.company.auth.login';
    protected $registerView = 'default.mobile.company.auth.register';
    protected $username  = 'username';

    /**
     * 除了退出其它多要自动验证
     * AuthController constructor.
     */
    public function __construct(){
        $this->middleware('guest:company', ['except' => 'logout']);
    }


    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request){
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        Auth::guard($this->getGuard())->login($this->create($request->all()));

        //注册记录表
        $user = auth()->guard('company')->user();
        $record = array();
        $record['uid'] = $user->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s',time());
        $record['login_type'] = 3;
        //检查是不是企业注册
        if(empty($request->openId)){
            $record['type'] = 1;
        }else{
            $record['type'] = 2;
        }
        //登录记录表和突访记录表
        CompanyLoginRecord::create($record);
        CompanyVisitRecord::create($record);

        //判断是什么类型注册
        if(!empty($request->email)){
            $user= auth()->guard('company')->user();
            $userInfo = (object)null;
            $userInfo->uid = $user->uid;
            $userInfo->email = $user->email;
            $userInfo->username = $user->username;
            $userInfo->password = $request->password;
            //添加到队列中
            $this->dispatch(new CompanyRegisterEmail($userInfo));
        }
        //删除验证码的session数据
        $request->session()->forget('mobile_verification');
        $request->session()->forget('mobile_verification_code');
    }
    /**
     * 手机注册提交
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request){

        $this->register($request);
        return response()->json(['status'=>0,'msg'=>'企业注册成功！','registerBasic'=>"/mobile/company/register_basic"]);

    }

    /**
     * 企业会员前台注册验证方法
     * @param array $data
     * @return mixed
     */
    protected function validator(array $data){
        $message = [
            'company_name.required' => '公司名称必须填写',
            'contacts.required' => '联系人必须填写',
            'mobile.mobile_verification' => '手机号码不正确',
            'mobCode.required' => '手机验证码不能为空',
            'mobCode.mobile_verification_code' => '手机号码和发送的验证码不匹配',
            'phone.check_phone' => '电话号码不正确',
            'username.required' => '用户名必须填写',
            'username.unique' => '该用户名已存在',
            'email.email' => '邮箱格式不正确',
            'password.required' => '密码必须填写',
            'password.between' => '密码必须在6-20位之间',
            'password.confirmed' => '确认密码和密码必须一致',
        ];
        return Validator::make($data, [
            'company_name' => 'required',
            'contacts' => 'required',
            'email' => 'email',
            'mobile' => 'mobile_verification',
            'mobCode' => 'required|mobile_verification_code:'.$data['mobile'],
            'phone' => 'check_mobile_phone',
            'username' => 'required|unique:company_users,username',
            'password' => 'required|between:6,20|confirmed',
        ],$message);
    }

    /**
     * 企业会员前台注册验证字段
     * @param array $data
     * @return static
     */
    protected function create(array $data){

        if(!empty($data['openid'])){
            if(empty($data['unionid'])){
                $data['unionid'] = NULL;
            }
            if($data['category'] == 'qq'){
                return CompanyUser::create([
                    'username' => $data['username'],
                    'password' => CustomPassword::make($data['password']),
                    'mobile' => $data['mobile'],
                    'contacts' => $data['contacts'],
                    'company_name' => $data['company_name'],
                    'email' => $data['email'],
                    'regip' => getIp(),
                    'phone' => trim($data['phone'],'-'),
                    'last_login_ip' => getIp(),
                    'qqopenid' => session('openid'),
                    'qqunionid' =>session('unionId')?session('unionId'):null,
                    'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                    'regtime' => date('Y-m-d H:i:s',time()),
                    'updatetime' => date('Y-m-d H:i:s',time()),
                    'last_login_time' => date('Y-m-d H:i:s',time())
                ]);
            }else{
                //微信
                return CompanyUser::create([
                    'username' => $data['username'],
                    'password' => CustomPassword::make($data['password']),
                    'mobile' => $data['mobile'],
                    'contacts' => $data['contacts'],
                    'company_name' => $data['company_name'],
                    'email' => $data['email'],
                    'regip' => getIp(),
                    'phone' => trim($data['phone'],'-'),
                    'last_login_ip' => getIp(),
                    'wechatmpopenid' => session('openid'),
                    'wechatunionid' => session('unionid')?session('unionid'):null,
                    'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                    'regtime' => date('Y-m-d H:i:s',time()),
                    'updatetime' => date('Y-m-d H:i:s',time()),
                    'last_login_time' => date('Y-m-d H:i:s',time())
                ]);
            }
        }else{
            return CompanyUser::create([
                'username' => $data['username'],
                'password' => CustomPassword::make($data['password']),
                'mobile' => $data['mobile'],
                'contacts' => $data['contacts'],
                'company_name' => $data['company_name'],
                'email' => $data['email'],
                'regip' => getIp(),
                'phone' => trim($data['phone'],'-'),
                'last_login_ip' => getIp(),
                'regtime' => date('Y-m-d H:i:s',time()),
                'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                'updatetime' => date('Y-m-d H:i:s',time()),
                'last_login_time' => date('Y-m-d H:i:s',time())
            ]);
        }
    }


    /**
     * 前台登录验证方法
     * @param Request $request
     */
    protected function validateLogin(Request $request){
        $message = [
            $this->loginUsername().'.required' => '用户名必须填写',
            $this->loginUsername().'.alpha_dash' => '用户仅允许字母、数字、底线_',
            $this->loginUsername().'.max' => '用户名称最多32个字符',
            'password.required' => '密码必须填写'
        ];
        $this->validate($request, [
            $this->loginUsername() => 'required|alpha_dash|max:32',
            'password' => 'required',
        ],$message);
    }
}
